package com.me.study.app.laserRange;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.me.study.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import me.hgj.jetpackmvvm.util.LogUtils;

/**
 * create author : FZW
 * create date  : 2024/9/30
 */
public class DiffuseView extends View {
    /**
     * 扩散圆圈颜色
     */
    private int mColor = getResources().getColor(R.color.purple_200);
    /**
     * 圆圈中心颜色
     */
    private int mCoreColor = getResources().getColor(R.color.purple_500);
    /**
     * 圆圈中心图片
     */
    private Bitmap mBitmap;
    /**
     * 中心圆半径
     */
    private float mCoreRadius = 150;
    /**
     * 扩散圆宽度
     */
    private int mDiffuseWidth = 3;
    /**
     * 最大宽度
     */
    private Integer mMaxWidth = 255;
    /**
     * 是否正在扩散中
     */
    private boolean mIsDiffuse = false;
    // 透明度集合
    private List<Integer> mAlphas = new ArrayList<>();
    // 扩散圆半径集合
    private List<Integer> mWidths = new ArrayList<>();
    private Paint mPaint;
    /**
     * 扫描的蓝牙设备信息
     */
    private List<ACSUtility.blePort> blueList = new ArrayList<>();
    private onViewClickListener mListener;

    /**
     * 蓝牙图片
     *
     * @param context
     */
    private Bitmap blueBitmap;

    public DiffuseView(Context context) {
        this(context, null);
    }

    public DiffuseView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public DiffuseView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DiffuseView, defStyleAttr, 0);
        mColor = a.getColor(R.styleable.DiffuseView_diffuse_color, mColor);
        mCoreColor = a.getColor(R.styleable.DiffuseView_diffuse_coreColor, mCoreColor);
        mCoreRadius = a.getFloat(R.styleable.DiffuseView_diffuse_coreRadius, mCoreRadius);
        mDiffuseWidth = a.getInt(R.styleable.DiffuseView_diffuse_width, mDiffuseWidth);
        mMaxWidth = a.getInt(R.styleable.DiffuseView_diffuse_maxWidth, mMaxWidth);
        int imageId = a.getResourceId(R.styleable.DiffuseView_diffuse_coreImage, -1);
        if (imageId != -1) mBitmap = BitmapFactory.decodeResource(getResources(), imageId);
        a.recycle();
    }

    private void init() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_scan_blue);
        blueBitmap = resizeBitmap(bitmap, 45, 45);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mAlphas.add(255);
        mWidths.add(0);
    }

    public interface onViewClickListener {
        void onBlueClick(ACSUtility.blePort blePort);
    }

    public void setOnBlueViewListener(onViewClickListener listener) {
        mListener = listener;
    }

    @Override
    public void invalidate() {
        if (hasWindowFocus()) {
            super.invalidate();
        }
    }

    @Override
    public void onDraw(Canvas canvas) {
        // 绘制扩散圆
        mPaint.setColor(mColor);
        for (int i = 0; i < mAlphas.size(); i++) {
            // 设置透明度
            Integer alpha = mAlphas.get(i);
            mPaint.setAlpha(alpha);
            // 绘制扩散圆
            Integer width = mWidths.get(i);
            canvas.drawCircle(getWidth() / 2, getHeight() / 2, mCoreRadius + width, mPaint);

            if (alpha > 0 && width < mMaxWidth) {
                mAlphas.set(i, alpha - 1);
                mWidths.set(i, width + 1);
            }
        }
        // 判断当扩散圆扩散到指定宽度时添加新扩散圆
        if (mWidths.get(mWidths.size() - 1) == mMaxWidth / mDiffuseWidth) {
            mAlphas.add(255);
            mWidths.add(0);
        }
        // 超过10个扩散圆，删除最外层
        if (mWidths.size() >= mDiffuseWidth + 1) {
            mWidths.remove(0);
            mAlphas.remove(0);
        }

        // 绘制中心圆及图片
        mPaint.setAlpha(255);
        mPaint.setColor(mCoreColor);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mCoreRadius, mPaint);

        if (mBitmap != null) {
            canvas.drawBitmap(mBitmap, getWidth() / 2 - mBitmap.getWidth() / 2
                    , getHeight() / 2 - mBitmap.getHeight() / 2, mPaint);
        }
        int size = blueList.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                ACSUtility.blePort blue = blueList.get(i);
                if (blueBitmap != null) {
                    canvas.drawBitmap(blueBitmap, blue.getLeft(), blue.getTop(), mPaint);
                }
            }
        }
        if (mIsDiffuse) {
            invalidate();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                for (ACSUtility.blePort circle : blueList) {
                    if (pointInCircle(event.getX(), event.getY(), circle)) {
//                        ToastUtils.showShort("x:" + circle.getLeft() + "----y:" + circle.getTop());
                        if (mListener != null) {
                            mListener.onBlueClick(circle);
                        }
                        return true;
                    }
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    private boolean pointInCircle(float x, float y, ACSUtility.blePort circle) {
        double distanceSquared = Math.pow(x - circle.getLeft(),2) + Math.pow(y - circle.getTop(),2);
        return distanceSquared <= Math.pow(45,20);
    }

    public void addRandomDevice(ACSUtility.blePort deviceBlue) {
        int circleX = getWidth() / 2;
        int circleY = getHeight() / 2;
        float circleT = circleY - mCoreRadius;
        float circleB = circleY + mCoreRadius;
        float circleL = circleX - mCoreRadius;
        float circleR = circleX + mCoreRadius;
        Random random = new Random();
        float x = random.nextInt(getWidth());
        float y = random.nextInt(getHeight());
        if (x > circleR && x < circleR + mMaxWidth / 2 || x < circleL && x > circleL - mMaxWidth / 2) {
            if (y > circleB && y < circleB + mMaxWidth / 2 || y < circleT && y > circleT - mMaxWidth / 2) {
                if (deviceBlue != null) {
                    deviceBlue.setLeft(x);
                    deviceBlue.setTop(y);
                    blueList.add(deviceBlue);
                    LogUtils.INSTANCE.debugInfo("-----满足条件----x:" + x + "------y:" + y);
                    invalidate();
                }
            } else {
                LogUtils.INSTANCE.debugInfo("-----Y 不满足条件-----x:" + x + "------y:" + y);
                addRandomDevice(deviceBlue);
            }
        } else {
            LogUtils.INSTANCE.debugInfo("-----X 不满足条件-----x:" + x + "------y:" + y);
            addRandomDevice(deviceBlue);
        }
    }

    /**
     * 开始扩散
     */
    public void start() {
        if (isDiffuse()) {
            return;
        }
        mIsDiffuse = true;
        invalidate();
    }

    /**
     * 停止扩散
     */
    public void stop() {
        mIsDiffuse = false;
        mAlphas.clear();
        mWidths.clear();
        blueList.clear();
        mAlphas.add(255);
        mWidths.add(0);
    }

    /**
     * 暂停扩散
     */
    public void pause() {
        mIsDiffuse = false;
        mAlphas.add(255);
        mWidths.add(0);
    }

    /**
     * 是否扩散中
     */
    public boolean isDiffuse() {
        return mIsDiffuse;
    }

    /**
     * 设置扩散圆颜色
     */
    public void setColor(int colorId) {
        mColor = colorId;
    }

    /**
     * 设置中心圆颜色
     */
    public void setCoreColor(int colorId) {
        mCoreColor = colorId;
    }

    /**
     * 设置中心圆图片
     */
    public void setCoreImage(int imageId) {
        mBitmap = BitmapFactory.decodeResource(getResources(), imageId);
    }

    /**
     * 设置中心圆半径
     */
    public void setCoreRadius(int radius) {
        mCoreRadius = radius;
    }

    /**
     * 设置扩散圆宽度(值越小宽度越大)
     */
    public void setDiffuseWidth(int width) {
        mDiffuseWidth = width;
    }

    /**
     * 设置最大宽度
     */
    public void setMaxWidth(int maxWidth) {
        mMaxWidth = maxWidth;
    }

    private Bitmap resizeBitmap(Bitmap bitmap, int targetWidth, int targetHeight) {
        return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true);
    }

}
